package com.rui.generator.controller;

import com.rui.common.annotation.PassToken;
import com.rui.common.base.BaseController;
import com.rui.common.exception.MyException;
import com.rui.common.util.Pages;
import com.rui.common.util.Res;
import com.rui.generator.entity.Generator;
import com.rui.generator.service.GeneratorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

/**
 * 代码生成器 Controller
 *
 * @author xr
 * @email xr@qq.com
 * @date 2020-01-01 00:00:00
 */
@Profile("dev")
@RestController
@RequestMapping("generator")
@Api(tags = "代码生成器")
public class GeneratorController extends BaseController {
    @Resource
    private GeneratorService generatorService;

    @GetMapping("page")
    @ApiOperation("代码生成器分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页的数量", dataType = "int", paramType = "query", required = true),
    })
    @PassToken
    public Res page() {
        Map<String, Object> map = pageInit();
        Pages<Generator> page = generatorService.page(map);
        return res.data(page);
    }

    @GetMapping("generator")
    @ApiOperation("代码生成")
    @ApiImplicitParam(name = "tables", value = "表名数组", allowMultiple = true, dataType = "String", required = true)
    @PassToken
    public void generator(String[] tables) {
        try {
            byte[] data = generatorService.generatorCode(tables);
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream; charset=UTF-8");
            IOUtils.write(data, response.getOutputStream());
        } catch (IOException e) {
            throw new MyException("IO流异常");
        }

    }

    @GetMapping("generator2")
    @ApiOperation("代码生成不打包(会覆盖)")
    @ApiImplicitParam(name = "tables", value = "表名数组", allowMultiple = true, dataType = "String", required = true)
    @PassToken
    public Res generator2(String[] tables) {
        Res res = new Res(200, "ok");
        try {
            generatorService.generatorCode2(tables);
        } catch (Exception e) {
            throw new MyException("IO流异常");
        }
        return res;
    }

}
